package cn.bigfire.wzdj.frame;

import com.alibaba.fastjson.JSON;
import cn.bigfire.wzdj.action.WZDJSender;
import cn.bigfire.wzdj.pojo.srcVo.Wzdj;
import cn.bigfire.wzdj.service.WZDJService;
import cn.bigfire.wzdj.util.Consts;
import cn.bigfire.wzdj.util.Stores;
import lombok.extern.slf4j.Slf4j;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
@Slf4j
public class PlayPanel extends JPanel {

    private final int rows = 9;
    private final int cols = 8;
    private final JLabel[][] matrix = new JLabel[rows][cols];


    private boolean isDragging = false; // 是否正在拖动
    private int startRow, startCol = -1;
    private int endRow, endCol = -1;

    public PlayPanel() {
        setLayout(new GridLayout()); // 两个矩阵水平排列
        // 初始化第一个矩阵
        JPanel panel1 = new JPanel(new GridLayout(rows, cols));
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                int index = i * cols + j;//下标
                int location = index + 1;
                JLabel jLabel = new JLabel();
                jLabel.setOpaque(true);
                Color land = Color.decode("#ECCD96");
                Color lawn = Color.decode("#68934D");
                if (myGridList.contains(location) || otherGridList.contains(location)) {
                    jLabel.setBackground(lawn);
                    jLabel.setBorder(BorderFactory.createLineBorder(land, 1));
                } else {
                    jLabel.setBackground(land);
                }
                matrix[i][j] = jLabel;
                panel1.add(matrix[i][j]);

                // 添加鼠标监听器
                int finalI = i;
                int finalJ = j;
                matrix[i][j].addMouseListener(new MouseAdapter() {
                    @Override
                    public void mousePressed(MouseEvent e) {
                        handleMousePressed(e, finalI, finalJ);
                    }

                    @Override
                    public void mouseReleased(MouseEvent e) {
                        handleMouseReleased(e, finalI, finalJ);
                    }
                });
                matrix[i][j].addMouseMotionListener(new MouseMotionAdapter() {
                    @Override
                    public void mouseDragged(MouseEvent e) {
                        handleMouseDragged(e);
                    }
                });

            }
        }
        add(panel1);
    }

    //游戏区 点击
    private void handleMousePressed(MouseEvent e, int row, int col) {
        if (e.getButton() == MouseEvent.BUTTON1) {//左键开始拖拽移动
            startRow = row;
            startCol = col;
            isDragging = true;
        }
    }

    //游戏区 松开
    private void handleMouseReleased(MouseEvent e,int row, int col) {
        if (MouseEvent.BUTTON1 == e.getButton()) {//左键
            if (isDragging) {
                isDragging = false;
                if (endRow == -1 || endCol == -1 || (startRow == endRow && startCol == endCol)) {//无移动
                    leftOk(row, col);
                } else {
                    leftDragOk();
                }
                reset();
            }
        } else if (MouseEvent.BUTTON2 == e.getButton()) {//中键
            centerOk(row,col);
        } else if (MouseEvent.BUTTON3 == e.getButton()) {//右键
            rightOk(row,col);
        }
    }

    /*
        三个事件
        空格子 拖拽可移动   左中右键无响应
        1英雄  拖拽可移动   左键无响应  中键查看信息  右键卖出
        2英雄  拖拽可移动	左键无响应  中键查看信息  右键卖出
        3英雄  拖拽可移动	左键合并    中键查看信息  右键卖出
        1神话  拖拽可移动	左键无响应  中键查看信息  右键强化
    */

    //鼠标左键拖拽完成
    public void leftDragOk() {
        int fromGrid = indexArr[startRow * cols + startCol];
        int toGrid = indexArr[endRow * cols + endCol];
        boolean myGrid = startRow > 4 && endRow > 4;
        System.out.printf("左键拖动 格%s->%s,who:%s%n", fromGrid, toGrid, myGrid ? "自己" : "对方");
        if (fromGrid < 0 || toGrid < 0 || !Stores.getInstance().getIsFight().get() || !myGrid) {
            return;
        }
        WZDJService.move(fromGrid, toGrid);
    }

    //鼠标左键点击事件
    public void leftOk(int row, int col) {
        int grid = indexArr[row * cols + col];//计算松手格子
        boolean myGrid = row > 4;
        System.out.printf("左键 格:%s,坐标[%s,%s]who:%s%n", grid, row, col, myGrid ? "自己" : "对方");
        if (grid < 0 || !Stores.getInstance().getIsFight().get() || !myGrid) {
            return;
        }
        CopyOnWriteArrayList<Wzdj.FightActorData> gridList = Stores.getInstance().getMyGridMap().getOrDefault(grid, new CopyOnWriteArrayList<>());
        if (gridList.size() == 3) {
            WZDJSender.rpcServerFightFighterSynthetic(grid);
        }
    }

    public void centerOk(int row,int col){
        int grid = indexArr[row * cols + col];//计算松手格子
        boolean myGrid = row > 4;
        System.out.printf("中键 格:%s,坐标[%s,%s]who:%s%n", grid, row, col,myGrid ? "自己" : "对方");
        if (grid < 0 || !Stores.getInstance().getIsFight().get()) {
            return;
        }
        List<Wzdj.FightActorData> gridList = myGrid ?
                Stores.getInstance().getMyGridMap().getOrDefault(grid, new CopyOnWriteArrayList<>()) :
                Stores.getInstance().getItGridMap().getOrDefault(grid, new CopyOnWriteArrayList<>());
        if (gridList.isEmpty()){
            return;
        }
        Wzdj.FightActorData fightActorData = gridList.get(0);
        String name = Consts.Fighter.nameById(fightActorData.getActorid());
        Integer lv = fightActorData.getLv();
        Integer speciallv = fightActorData.getSpeciallv();
        String format = String.format("%s(%s)%s:%s%n", name, lv, speciallv, JSON.toJSONString(fightActorData));
        log.info(format);
        WZDJMainFrame.consoleTextArea.append(format);
    }

    public void rightOk(int row, int col) {
        int grid = indexArr[row * cols + col];//计算松手格子
        boolean myGrid = row > 4;
        System.out.printf("右键 格:%s,坐标[%s,%s]who:%s%n", grid, row, col, myGrid ? "自己" : "对方");
        if (grid < 0 || !Stores.getInstance().getIsFight().get() || !myGrid) {
            return;
        }
        ConcurrentHashMap<Integer, CopyOnWriteArrayList<Wzdj.FightActorData>> myGridMap = Stores.getInstance().getMyGridMap();
        List<Wzdj.FightActorData> gridList = myGridMap.getOrDefault(grid, new CopyOnWriteArrayList<>());
        if (gridList.isEmpty()) {
            return;
        }
        Wzdj.FightActorData fightActorData = gridList.get(0);
        String name = Consts.Fighter.nameById(fightActorData.getActorid());
        if (WZDJService.isBig(fightActorData.getActorid())) {
            //判断可强化
            if (fightActorData.getActorid().equals("f_5004")||fightActorData.getActorid().equals("f_5015")) {//无极  强化
                WZDJSender.rpcServerFightFighterAttrsShow(fightActorData.getId());
                WZDJSender.rpcServerFightFighterOperate(fightActorData.getId());
            }
        } else {//小的卖出
            fightActorData.setGrid(grid);
            System.out.printf("删除 单元格:%s,id:%s 英雄:%s%n", grid, fightActorData.getId(), name);
            WZDJService.remove(fightActorData);
        }
    }


    private void reset() {
        startRow = -1;
        startCol = -1;
        endRow = -1;
        endCol = -1;
    }

    private void handleMouseDragged(MouseEvent e) {
        if (isDragging) {
            int x = e.getXOnScreen();
            int y = e.getYOnScreen();
            Point locationOnScreen = getLocationOnScreen();
            int panelX = x - locationOnScreen.x;
            int panelY = y - locationOnScreen.y;
            // 将屏幕坐标转换为面板内的网格坐标
            int col = (panelX + getInsets().left) / (getWidth() / cols);
            int row = (panelY + getInsets().top) / (getHeight() / rows);
            // 确保坐标在有效范围内
            row = Math.max(0, Math.min(row, rows - 1));
            col = Math.max(0, Math.min(col, cols - 1));
            endRow = row;
            endCol = col;
            // 这里可以根据需要处理拖动逻辑，例如高亮显示或交换单元格内容
//            log.info("Dragging over (" + row + ", " + col + ")");
        }
    }

    Integer[] indexArr = new Integer[]{
            -1, -1, -1, -1, -1, -1, -1, -1,
            -1, 2, 5, 8, 11, 14, 17, -1,
            -1, 1, 4, 7, 10, 13, 16, -1,
            -1, 0, 3, 6, 9, 12, 15, -1,
            -1, -1, -1, -1, -1, -1, -1, -1,
            -1, 0, 3, 6, 9, 12, 15, -1,
            -1, 1, 4, 7, 10, 13, 16, -1,
            -1, 2, 5, 8, 11, 14, 17, -1,
            -1, -1, -1, -1, -1, -1, -1, -1,
    };

    Integer[] myGridArr = new Integer[]{42, 50, 58, 43, 51, 59, 44, 52, 60, 45, 53, 61, 46, 54, 62, 47, 55, 63};
    List<Integer> myGridList = Arrays.asList(myGridArr);
    Integer[] otherGridArr = new Integer[]{26, 18, 10, 27, 19, 11, 28, 20, 12, 29, 21, 13, 30, 22, 14, 31, 23, 15};
    List<Integer> otherGridList = Arrays.asList(otherGridArr);


    public void update(Map<Integer, CopyOnWriteArrayList<Wzdj.FightActorData>> gridMap, boolean isMy) {
        Integer[] gridArr = isMy ? myGridArr : otherGridArr;
        for (Map.Entry<Integer, CopyOnWriteArrayList<Wzdj.FightActorData>> entity : gridMap.entrySet()) {
            Integer grid = entity.getKey();
            List<Wzdj.FightActorData> actorList = entity.getValue();
            if (actorList.isEmpty()) {
                Integer location = gridArr[grid];
                int row = location / cols;
                int col = location % cols - 1;
                matrix[row][col].setText("");
            } else {
                Integer location = gridArr[grid];
                int row = location / cols;
                int col = location % cols - 1;

                JLabel tmpJLabel = matrix[row][col];
                String name = Consts.Fighter.nameById(actorList.get(0).getActorid());
                String text = name + "(" + actorList.size() + ")";
                tmpJLabel.setHorizontalAlignment(SwingConstants.CENTER);
                tmpJLabel.setText(text);
            }
        }
    }

    public void clear() {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                matrix[i][j].setText("");
            }
        }
    }


//    @Test
//    @SneakyThrows
//    public void test() {
//        for (int i = 0; i < 19; i++) {
//            log.info("----------------");
//            System.out.printf("num:%s,取整:%s,取余:%s%n", i, i / cols, i % cols);
////            log.info(i / cols);
////            log.info(i % cols);
//            log.info("----------------");
//        }
////        int num = 26;
//    }

//
//    public static void main(String[] args) {
//        HashMap<Integer, List<Wzdj.FightActorData>> gridMap = new HashMap<>();
//        PlayPanel playPanel = new PlayPanel();
//        SwingUtilities.invokeLater(() -> {
//            JFrame frame = new JFrame("Matrix Panel Example");
//            frame.setSize(800, 600);
//            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//            playPanel.setPreferredSize(new Dimension(800, 600));
//            List<Wzdj.FightActorData> dataList = new ArrayList<>();
//            Wzdj.FightActorData fightActorData = new Wzdj.FightActorData();
//            fightActorData.setActorid("f_1001");
//            dataList.add(fightActorData);
//            gridMap.put(0, dataList);
////            gridMap.put(1, dataList);
////            gridMap.put(2, dataList);
////            gridMap.put(3, dataList);
//            playPanel.update(gridMap, true);
//            playPanel.update(gridMap, false);
//
//            frame.add(playPanel);
//            frame.setVisible(true);
//        });
//
//        ThreadUtil.execAsync(() -> {
//            ThreadUtil.sleep(10 * 1000);
//            log.info("移动0->5");
//            List<Wzdj.FightActorData> fromList = gridMap.getOrDefault(0, new ArrayList<>());
//            List<Wzdj.FightActorData> toList = gridMap.getOrDefault(5, new ArrayList<>());
//            gridMap.put(0, toList);
//            gridMap.put(5, fromList);
//            playPanel.update(gridMap, true);
//        });
//    }

}
